import React from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import Sidebar from './Sidebar'
import { useTranslation } from 'react-i18next';
import LoginModal from './LoginModal';
import LogoutConfirmModal from './LogoutConfirmModal';
import vipIcon from '../assets/images/vip.png';
import LogoutIcon from '../assets/images/bxs-log-out-circle.png';
import ptVip from '@/assets/images/ptVip.png'
import xyVip from '@/assets/images/xyVip.png'
import zzVip from '@/assets/images/zzVip.png'
import freeVip from '@/assets/images/freeVip.png'
import { useUserProfile } from '../hooks/useUserProfile';
import { getDynamicFonts } from '@/utils/fontUtils';
import { getTokensBalanceByUuid } from '@/api/userService';
import TokenBalance from './TokenBalance';

interface NavigationProps {
  isMobile: boolean
  sidebarCollapsed: boolean
  sidebarVisible: boolean
  toggleSidebar: () => void
  headerHidden?: boolean
  activeTab: string
  setActiveTab: (key: string) => void
  onChatCollectionClick?: () => void
}

// 选项卡菜单组件
function TabMenu({ isMobile, activeTab, setActiveTab }: { isMobile: boolean, activeTab: string, setActiveTab: (key: string) => void }) {
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);

  const tabIcons: Record<string, string> = {
    anime_girl: 'fas fa-user-ninja',
    anime_man: 'fas fa-user-astronaut',
    girl: 'fas fa-female',
    man: 'fas fa-male',
  };
  const tabs = [
    { key: 'anime_girl', label: t('home.tabs.anime_girl') },
    { key: 'anime_man', label: t('home.tabs.anime_man') },
    // { key: 'girl', label: t('home.tabs.girl') },
    // { key: 'man', label: t('home.tabs.man') },
  ];
  const activeColor = 'rgb(252, 118, 138)'; //被选中的字体颜色

  // refs for tab内容
  const contentRefs = React.useRef<(HTMLSpanElement | null)[]>([]);
  const [lineStyle, setLineStyle] = React.useState<{ left: number; width: number }>({ left: 0, width: 0 });

  React.useEffect(() => {
    const idx = tabs.findIndex(tab => tab.key === activeTab);
    const el = contentRefs.current[idx];
    if (el) {
      const rect = el.getBoundingClientRect();
      const parentRect = el.parentElement?.parentElement?.getBoundingClientRect();
      if (parentRect) {
        setLineStyle({ left: rect.left - parentRect.left - 8, width: rect.width + 16 });
      }
    }
  }, [activeTab, isMobile, i18n.language]);

  const handleTabClick = (key: string) => {
    setActiveTab(key);
  };

  // 移动端 
  if (isMobile) {
    return (
      <div className="fixed left-0 top-16 w-full z-40 bg-[rgb(33,33,33)] shadow-md" style={{ width: '100vw', position: 'fixed', left: 0, right: 0 }}>
        <div className="px-1">
          <div className="flex w-full relative justify-center" >
            {tabs.map((tab, idx) => (
              <button
                key={tab.key}
                className="h-[3rem] flex flex-row items-center justify-center text-center font-bold transition-colors duration-200 bg-transparent outline-none relative"
                style={{
                  boxShadow: 'none',
                  fontSize: '0.7rem',
                  fontFamily: dynamicFonts.font3,
                  paddingLeft: window.innerWidth <= 320 ? '0.5rem' : '0.75rem', // 极小屏幕减小内边距
                  paddingRight: window.innerWidth <= 320 ? '0.5rem' : '0.75rem',
                  paddingTop: '0.75rem',
                  paddingBottom: '0.75rem'
                }}
                onClick={() => handleTabClick(tab.key)}
              >
                <span ref={el => contentRefs.current[idx] = el} className="flex flex-row items-center justify-center" style={{ whiteSpace: 'nowrap' }}>
                  <i
                    className={`${tabIcons[tab.key]} mr-1`}
                    style={{
                      color: activeTab === tab.key ? activeColor : 'white',
                      transition: 'color 0.2s',
                      fontSize: window.innerWidth <= 320 ? '0.875rem' : window.innerWidth <= 375 ? '1rem' : '1.125rem', // 响应式图标大小
                      marginRight: window.innerWidth <= 320 ? '0.25rem' : '0.5rem' // 极小屏幕减小图标与文字间距
                    }}
                  />
                  <span style={{
                    color: activeTab === tab.key ? activeColor : 'white',
                    fontWeight: activeTab === tab.key ? 700 : 500,
                    transition: 'color 0.2s',
                    fontSize: window.innerWidth <= 320 ? '0.55rem' : window.innerWidth <= 375 ? '0.6rem' : '0.7rem' // 三级响应式字体大小
                  }}>{tab.label}</span>
                </span>
              </button>
            ))}
            {/* 横向滑动横线 */}
            <span
              className="absolute"
              style={{
                left: lineStyle.left,
                width: lineStyle.width,
                bottom: 0,
                height: 3,
                background: activeColor,
                borderRadius: 2,
                transition: 'left 0.3s cubic-bezier(.4,0,.2,1), width 0.3s cubic-bezier(.4,0,.2,1)',
                zIndex: 2,
                display: 'block',
              }}
            />
          </div>
        </div>
      </div>
    );
  }
  return (
    // 选项卡的菜单 pc端
    <div className="flex relative ">
      {tabs.map((tab, idx) => (
        <button
          key={tab.key}
          className="flex h-[4rem] flex-row items-center justify-center px-4 py-2 rounded border-none bg-transparent outline-none relative transition-colors duration-200"
          style={{ boxShadow: 'none', fontFamily: dynamicFonts.font3 }}
          onClick={() => handleTabClick(tab.key)}
        >
          {/* 按钮里的文字  */}
          <span ref={el => contentRefs.current[idx] = el} className="flex flex-row items-center justify-center text-[0.9rem]">
            <i className={`${tabIcons[tab.key]}  mr-2`} style={{ color: activeTab === tab.key ? activeColor : 'white', transition: 'color 0.2s' }}></i>
            <span style={{ color: activeTab === tab.key ? activeColor : 'white', fontWeight: activeTab === tab.key ? 700 : 500, transition: 'color 0.2s' }}>{tab.label}</span>
          </span>
        </button>
      ))}
      {/* 横向滑动横线 */}
      <span
        className="absolute"
        style={{
          left: lineStyle.left,
          width: lineStyle.width,
          bottom: 0,
          height: 5,
          background: activeColor,
          borderRadius: 2,
          transition: 'left 0.3s cubic-bezier(.4,0,.2,1), width 0.3s cubic-bezier(.4,0,.2,1)',
          zIndex: 2,
          display: 'block',
        }}
      />
    </div>
  );
}

// Header组件
function Header({
  isMobile,
  sidebarCollapsed,
  sidebarVisible,
  toggleSidebar,
  headerHidden,
  activeTab,
  setActiveTab
}: NavigationProps) {
  const location = useLocation();
  const navigate = useNavigate();
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);

  // 使用统一的用户头像管理 hook
  const {
    isLoggedIn,
    userData,
    showLoginModal,
    isRegisterMode,
    showLogoutButton,
    logoutRef,
    avatarBtnRef,
    showLogoutConfirm,
    confirmLogout,
    cancelLogout,
    handleLoginClick,
    handleRegisterClick,
    handleLoginSuccessAndUpdateTab,
    handleLogoutClick,
    withAvatarResize,
    toggleProfileDropdown,
    closeLoginModal,
    navigateToSubscription
  } = useUserProfile();

  // 包装登录成功处理，添加 setActiveTab 参数
  const handleLoginSuccessWithTab = () => {
    handleLoginSuccessAndUpdateTab(setActiveTab);
  };

  return (
    <>
      <header
        className={`h-16 flex border-b border-b-[rgb(51,51,57)] text-xl fixed top-0 ${isMobile ? 'px-2' : 'px-6'} left-0 right-0 z-30 bg-[rgb(19,19,19)] transition-transform duration-300 ${headerHidden ? '-translate-y-full' : 'translate-y-0'}`}
        style={{ "--container-padding": "1.5rem" } as React.CSSProperties}
      >
        {/* header里的内容盒子 */}
        <div
          className=" cursor-pointer flex  w-full justify-between"
          aria-label={isMobile ? (sidebarVisible ? '关闭菜单' : '打开菜单') : (sidebarCollapsed ? '展开侧边栏' : '收起侧边栏')}
        >
          {/* 左侧的部分  */}
          <div className='flex items-center relative' style={{
            width: isMobile ? (window.innerWidth <= 320 ? '60%' : '') : 'auto',
            overflow: 'hidden'
          }}>
            {/* 控制侧边栏展开和收起的按钮 - 移动端与侧边栏菜单图标对齐 */}
            <i
              onClick={toggleSidebar}
              className="fas fa-bars hover:text-pink-500 transition-colors duration-200"
              style={{
                marginRight: window.innerWidth <= 320 ? '0.3rem' : isMobile ? '0.3rem' : '1rem',
                marginLeft: window.innerWidth <= 320 ? '0rem' : isMobile ? '0.2rem' : '0',
                fontSize: isMobile ? '1.5rem' : '1.8rem'
              }}
            />
            {/* logo部分  */}
            <div onClick={() => navigate('/')} className="font-logoFont cursor-pointer ">
              <span
                className={`text-white ${window.innerWidth <= 320 ? "text-xl" : isMobile ? "text-2xl" : "text-3xl"}`}
                style={{
                  textShadow: '1px 1px 0 #111,2px 2px 0 #222,3px 3px 0 #333,4px 4px 6px rgba(0,0,0,0.6)',
                  marginLeft:"0.5rem"
                }}>Know</span>
              <span
                className={`text-pink-500 ${window.innerWidth <= 320 ? "text-2xl" : isMobile ? "text-3xl" : "text-4xl"}`}
                style={{
                  textShadow: '1px 1px 0 #881337,2px 2px 0 #701a29,3px 3px 0 #500f1c,4px 4px 6px rgba(0,0,0,0.6)',
                  fontStyle: 'italic',
                  fontWeight: 600,
                  marginLeft: window.innerWidth <= 320 ? '0.1rem' : '0.2rem'
                }}
              >
                1
              </span>
            </div>

            {/* 选项卡 只在Home页面显示，且移动端侧边栏弹出时隐藏TabMenu */}
            <div className={isMobile ? 'ml-2' : 'ml-20'} style={{ fontFamily: dynamicFonts.font2 }}>
              {location.pathname === '/' && (!isMobile || (isMobile && !sidebarVisible)) && (
                <TabMenu isMobile={isMobile} activeTab={activeTab} setActiveTab={setActiveTab} />
              )}
            </div>
          </div>
          {/* 右侧的部分：按钮等  */}
          <div className="flex space-x-1 items-center">
            {/* 未登录时显示注册和登录按钮 */}
            {!isLoggedIn && (
              <>
                {/* 移动端注册按钮 */}
                <button
                  data-redirect-url="https://candy.ai/"
                  data-action="click->main#openRegistrationModal"
                  data-main-target="registerButton"
                  className=" text-[0.9rem] h-8 px-2 md:px-4 py-1.5 bg-[#E75275] rounded-lg items-center gap-2 inline-flex cursor-pointer mr-1"
                  onClick={handleRegisterClick}
                >
                  <span>
                    {t('common.JoinFree')}
                  </span>
                </button>
                {/* 登录按钮 */}
                <button
                  className="bg-[rgb(19,19,19)] border border-[rgb(221,65,81)] transition-colors text-[rgb(221,65,81)] text-[0.9rem] rounded-[0.5rem] px-2  font-medium focus:outline-none focus:border-[rgb(221,65,81)] hover:border-[rgb(221,65,81)]"
                  onClick={handleLoginClick}
                >
                  <span>{t('common.login')}</span>
                </button>
              </>
            )}
            {/* 余额展示区域 */}
            {isLoggedIn && (
              <div className='mr-2 flex items-center'>
                <TokenBalance userData={userData} isMobile={isMobile} />
              </div>
            )}
            {/* 登录后显示头像部分 */}
            {isLoggedIn && userData && (
              <div className={window.innerWidth <= 320 ? 'ml-1' : isMobile ? 'ml-2' : 'ml-4'}>
                <div ref={avatarBtnRef} className="relative flex items-center mr-0" style={{ height: 32, minWidth: window.innerWidth <= 320 ? 24 : 32 }}>
                  <div
                    className={`rounded-full bg-gradient-to-r p-0.5 flex-shrink-0 flex items-center justify-center ${window.innerWidth <= 320 ? 'w-6 h-6' : isMobile ? 'w-8 h-8' : 'w-9 h-9'
                      }`}
                    style={{
                      minWidth: window.innerWidth <= 320 ? 24 : isMobile ? 28 : 32,
                      minHeight: window.innerWidth <= 320 ? 24 : isMobile ? 28 : 32,
                      cursor: 'pointer',
                      padding: window.innerWidth <= 320 ? '1px' : '2px' // 极小屏幕减小内边距
                    }}
                    onClick={toggleProfileDropdown}
                  >
                    <div className="w-full h-full rounded-full overflow-hidden bg-app-dark flex items-center justify-center">
                      {userData.user_avatar ? (
                        <img src={withAvatarResize(userData.user_avatar)} alt="avatar" className="w-full h-full object-cover transition-opacity duration-300" />
                      ) : (
                        <div className="w-full h-full bg-gray-600 flex items-center justify-center animate-pulse">
                          <i className={`fas fa-user text-gray-400 ${window.innerWidth <= 320 ? 'text-[0.5rem]' : 'text-xs'}`}></i>
                        </div>
                      )}
                    </div>
                  </div>
                  {/* My Profile和下拉icon - 在极小屏幕上只显示头像，中等屏幕隐藏文字，PC端显示全部 */}
                  {userData.login_type === 'google' && window.innerWidth > 320 && (
                    <>
                      {(!isMobile || window.innerWidth > 320) && (
                        <>
                          <div onClick={toggleProfileDropdown} className="flex flex-col items-center">
                            <div className="flex items-center justify-center">
                              <span className="flex items-center">
                                {/* 会员图标，保证与myProfile文字同行且完整显示 */}
                                {userData.vip_live === 1 && (
                                  <img src={ptVip} alt="PT VIP" className="h-6 w-6 -mt-[0.5rem]" style={{ objectFit: 'cover' }} />
                                )}
                                {userData.vip_live === 2 && (
                                  <img src={xyVip} alt="XY VIP" className="h-6 w-6 -mt-[0.5rem]" style={{ objectFit: 'contain' }} />
                                )}
                                {userData.vip_live === 3 && (
                                  <img src={zzVip} alt="ZZ VIP" className="h-6 w-6 -mt-[0.5rem]" style={{ objectFit: 'contain' }} />
                                )}
                                {/* {(userData.vip_live === null || userData.vip_live === 0) && (
                                  <img src={freeVip} alt="Free User" className="h-6 w-6 -mt-[0.5rem]" style={{ objectFit: 'contain' }} />
                                )} */}
                                <span
                                  className="text-white font-medium max-w-[100px] text-[0.85rem] truncate cursor-pointer select-none text-center"
                                  style={{ fontFamily: dynamicFonts.font3 }}

                                >
                                  {t('common.myProfile')}
                                </span>
                              </span>
                            </div>
                            <p style={{ fontFamily: dynamicFonts.font3 }} className="text-xs text-gray-300 leading-tight text-center">
                              {userData.vip_live === 1 ? t('subscription.packages.names.prelude') :
                                userData.vip_live === 2 ? t('subscription.packages.names.affinity') :
                                  userData.vip_live === 3 ? t('subscription.packages.names.soulmate') :
                                    t('buyToken.membershipTypes.free.description')}
                            </p>
                          </div>
                        </>

                      )}
                      <i
                        className={`fas fa-chevron-${showLogoutButton ? 'up' : 'down'} ${isMobile ? 'ml-1 mr-1' : 'ml-3 mr-2'} text-xs text-gray-400 cursor-pointer`}
                        style={{ marginTop: 2 }}
                        onClick={toggleProfileDropdown}
                      />
                    </>
                  )}
                  {/* 进入订阅页面和退出登录的按钮 */}
                  {userData.login_type === 'google' && showLogoutButton && (
                    <div
                      ref={logoutRef}
                      style={{ backgroundColor: "rgb(24,24,27)", cursor: "pointer", fontFamily: dynamicFonts.font3 }}
                      className="w-[12rem] absolute top-full right-0 mt-2 bg-[24,24,27] text-white text-[0.85rem] min-w-[140px] px-0 py-2 rounded-lg shadow-lg z-[100]"
                    >
                      {/* 进入订阅页面  */}
                      <div
                        className="flex items-center px-4 py-2 cursor-pointer hover:bg-[rgba(54,65,83,0.7)] transition-colors"
                        onClick={() => navigate('/subscriptions')}
                      >
                        {/* 会员时显示当前会员图标+升级会员，非会员显示vipIcon+Subscription */}
                        {userData.vip_live === 1 && (
                          <img src={ptVip} alt="PT VIP" className="w-10 h-10 -ml-[0.5rem] -mt-[0.8rem]" style={{ objectFit: 'contain' }} />
                        )}
                        {userData.vip_live === 2 && (
                          <img src={xyVip} alt="XY VIP" className="w-10 h-10 -ml-[0.5rem] -mt-[0.8rem]" style={{ objectFit: 'contain' }} />
                        )}
                        {userData.vip_live === 3 && (
                          <img src={zzVip} alt="ZZ VIP" className="w-10 h-10 -ml-[0.5rem] -mt-[0.8rem]" style={{ objectFit: 'contain' }} />
                        )}
                        {(userData.vip_live === null || userData.vip_live === 0) && (
                          <img src={vipIcon} alt="vip" className="w-7 h-7 -ml-[0.3rem] mr-2" />
                        )}
                        <span
                          className="select-none"
                          style={{
                            color: '#fff',
                          }}
                        >
                          {/* 会员显示"升级会员"，非会员显示"订阅" */}
                          {(userData.vip_live === 1 || userData.vip_live === 2 || userData.vip_live === 3)
                            ? t('subscription.upgrade')
                            : t('subscription.title')}
                        </span>
                      </div>
                      {/* 进入我的页面  */}
                      <div
                        className="flex items-center px-4 py-2 cursor-pointer hover:bg-[rgba(54,65,83,0.7)] transition-colors"
                        onClick={() => navigate('/settings')}
                      >
                        <i className="fas fa-user-cog w-6 h-6 mr-2 flex items-center justify-center" style={{ color: '#fff', fontSize: '1.2rem' }}></i>
                        <span
                          className="select-none"
                          style={{
                            color: '#fff'
                          }}
                        >
                          {t('common.mine')}
                        </span>
                      </div>
                      {/* 进入我的页面  */}
                      {/* <div
                        className="flex items-center px-4 py-2 cursor-pointer hover:bg-[rgba(54,65,83,0.7)] transition-colors"
                        onClick={() => navigate('/settings')}
                      >
                        <i className="fas fa-cog w-6 h-6 mr-2 flex items-center justify-center" style={{ color: '#fff', fontSize: '1.2rem' }}></i>
                        <span
                          className="select-none"
                          style={{
                            color: '#fff'
                          }}
                        >
                          {t('common.mine')}
                        </span>
                      </div> */}
                      {/* 退出登录  */}
                      <div
                        className="flex items-center px-4 py-2 cursor-pointer hover:bg-[rgba(54,65,83,0.7)] transition-colors"
                        onClick={handleLogoutClick}
                      >
                        <img src={LogoutIcon} alt="logout" className="w-6 h-6 mr-2" />
                        <span
                          className="select-none"
                          style={{
                            color: '#fff'
                          }}
                        >
                          {t('common.logout')}
                        </span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* 登录弹窗 */}
      <LoginModal
        show={showLoginModal}
        onClose={closeLoginModal}
        onLoginSuccess={handleLoginSuccessWithTab}
        initialRegister={isRegisterMode}
        activeTab={activeTab}
      />

      {/* 退出登录确认弹窗 */}
      <LogoutConfirmModal
        show={showLogoutConfirm}
        onClose={cancelLogout}
        onConfirm={confirmLogout}
      />
    </>
  );
}

// PC端侧边栏
function DesktopSidebar({ isMobile, sidebarCollapsed }: { isMobile: boolean, sidebarCollapsed: boolean }) {
  if (isMobile) return null;

  return (
    <aside
      className={`bg-[rgb(19,19,19)] border-r border-r-[rgb(51,51,57)] text-white transition-all duration-300 fixed left-0 top-16 z-40 ${sidebarCollapsed ? 'w-18' : 'w-56'}`}
      style={{
        height: 'calc(100vh - 4rem)',
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        padding: 0
      }}
    >
      <Sidebar
        sidebarCollapsed={!sidebarCollapsed}
        isMobile={isMobile}
        activeTab=""
        setActiveTab={() => { }}
      />
    </aside>
  );
}

// 移动端侧边栏
function MobileSidebar({
  isMobile,
  sidebarVisible,
  sidebarCollapsed,
  toggleSidebar,
  onChatCollectionClick
}: {
  isMobile: boolean,
  sidebarVisible: boolean,
  sidebarCollapsed: boolean,
  toggleSidebar: () => void,
  onChatCollectionClick?: () => void
}) {
  if (!isMobile || !sidebarVisible) return null;

  return (
    <>
      {/* 毛玻璃遮罩层 - 高于底部导航栏的层级 */}
      <div
        className="fixed inset-0 top-16 transition-all duration-300"
        style={{
          zIndex: 60, // 高于底部导航栏的 z-50
          backdropFilter: 'blur(8px)',
          WebkitBackdropFilter: 'blur(8px)',
          backgroundColor: 'rgba(0, 0, 0, 0.4)',
        }}
        onClick={toggleSidebar} // 点击遮罩关闭侧边栏
      />
      {/* 侧边栏 - 确保高于底部导航栏 */}
      <div
        className="fixed top-16 left-0 h-full transition-transform duration-300 bg-[rgb(19,19,19)] text-white"
        style={{
          zIndex: 70, // 高于遮罩层
          width: sidebarCollapsed ? '4rem' : '13rem',
          display: 'flex',
          flexDirection: 'column',
          height: 'calc(100vh - 4rem)'
        }}
      >
        <Sidebar
          sidebarCollapsed={!sidebarCollapsed}
          isMobile={isMobile}
          activeTab=""
          setActiveTab={() => { }}
          onCloseSidebar={toggleSidebar}
          onChatCollectionClick={onChatCollectionClick}
        />
      </div>
    </>
  );
}

// 主导航组件
export default function Navigation(props: NavigationProps) {
  return (
    <>
      <Header {...props} />
      <DesktopSidebar isMobile={props.isMobile} sidebarCollapsed={props.sidebarCollapsed} />
      <MobileSidebar
        isMobile={props.isMobile}
        sidebarVisible={props.sidebarVisible}
        sidebarCollapsed={props.sidebarCollapsed}
        toggleSidebar={props.toggleSidebar}
        onChatCollectionClick={props.onChatCollectionClick}
      />
    </>
  );
} 